package com.qf.java2107.yb.hotel.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器，一站解决中文乱码
 * @author yb
 * @version 1.0
 * @date 2021-10-16
 **/
@WebFilter("/*")
public class CharsetEncodingFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        //一站式解决中文乱码，Servlet才有可能出现中文乱码
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //对一些文件进行过滤，然后进行放行
        String uri = request.getRequestURI();
        if(uri.endsWith(".jsp") || uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".html")) {
            chain.doFilter(request, response);
            return;
        }

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }
}
